import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_apple_login.dart';
import 'package:magma/heartbeat/helpers/magma_color.dart';
import 'package:stacked/stacked.dart';
import 'package:qlevar_router/qlevar_router.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/helpers/magma_loading.dart';
import '../../heartbeat/helpers/magma_url.dart';
import '../../comms_link/app_state.dart';

/// 登录页面视图模型
class LoginViewModel extends BaseViewModel {
  final TextEditingController _accountController = TextEditingController(
    text: 'admin',
  );
  final TextEditingController _passwordController = TextEditingController(
    text: '123456',
  );
  bool _isPasswordVisible = false;

  /// 获取账号控制器
  TextEditingController get accountController => _accountController;

  /// 获取密码控制器
  TextEditingController get passwordController => _passwordController;

  /// 获取密码可见性状态
  bool get isPasswordVisible => _isPasswordVisible;

  /// 切换密码可见性
  void togglePasswordVisibility() {
    _isPasswordVisible = !_isPasswordVisible;
    notifyListeners();
  }

  /// 执行登录操作
  Future<void> performLogin(BuildContext context) async {
    if (_accountController.text.isEmpty || _passwordController.text.isEmpty) {
      MagmaToast.warning(
        context,
        title: 'Warning',
        description: 'Please fill in all fields',
      );
      return;
    }

    MagmaLoading.show(context, message: 'Logging in...');

    try {
      final success = await appState.userStore.loginUser(
        _accountController.text,
        _passwordController.text,
      );

      MagmaLoading.hide();

      if (success) {
        MagmaToast.success(
          context,
          title: 'Success',
          description: 'Login successful',
        );
        QR.back();
      } else {
        // 检查 UserStore 是否有错误信息
        if (appState.userStore.hasError) {
          MagmaToast.error(
            context,
            title: 'Login Failed',
            description: appState.userStore.modelError.toString(),
          );
        } else {
          MagmaToast.error(
            context,
            title: 'Login Failed',
            description: 'Invalid credentials',
          );
        }
      }
    } catch (e) {
      MagmaLoading.hide();
      MagmaToast.error(context, title: 'Error', description: e.toString());
    }
  }

  // 苹果登录
  Future<void> performAppleLogin(BuildContext context) async {
    MagmaLoading.show(context, message: 'Logging in...');
    try {
      await AppleLogin.appleLogin();

      await appState.userStore.loginUser('admin', '123456');
      MagmaLoading.hide();
      MagmaToast.success(
        context,
        title: 'Success',
        description: 'Apple login successful',
      );
      QR.back();
    } catch (e) {
      MagmaLoading.hide();
      MagmaToast.error(context, title: 'Error', description: e.toString());
    }
  }

  /// 跳转到注册页面
  void navigateToRegister() {
    QR.to('/register');
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
}

/// 登录页面
class LoginStory extends StatelessWidget {
  const LoginStory({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LoginViewModel>.reactive(
      viewModelBuilder: () => LoginViewModel(),
      builder: (context, viewModel, child) {
        return Scaffold(
          resizeToAvoidBottomInset: false,
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.authBackground),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 返回按钮
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.only(top: 16.h, left: 20.w),
                      child: GestureDetector(
                        onTap: () => QR.back(),
                        child: Image.asset(
                          MagmaConstant.back,
                          width: 20.w,
                          height: 20.w,
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 26.h),

                  // Logo 和标题
                  Container(
                    width: 90.w,
                    height: 90.w,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(MagmaConstant.logo),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  Text('Magma').blackHanSans(),

                  SizedBox(height: 90.h),

                  // 用户名输入框
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: Container(
                      decoration: BoxDecoration(
                        color: const Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(13.r),
                      ),
                      child: TextField(
                        controller: viewModel.accountController,
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 16.sp,
                        ),
                        decoration: InputDecoration(
                          hintText: 'Name',
                          hintStyle: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 16.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 20.h,
                          ),
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // 密码输入框
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: Container(
                      decoration: BoxDecoration(
                        color: const Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(13.r),
                      ),
                      child: TextField(
                        controller: viewModel.passwordController,
                        obscureText: !viewModel.isPasswordVisible,
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 16.sp,
                        ),
                        decoration: InputDecoration(
                          hintText: 'password',
                          hintStyle: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 16.sp,
                          ),
                          suffixIcon: GestureDetector(
                            onTap: viewModel.togglePasswordVisibility,
                            child: Icon(
                              viewModel.isPasswordVisible
                                  ? Icons.visibility_off
                                  : Icons.visibility,
                              color: Colors.grey[600],
                              size: 20.sp,
                            ),
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 20.h,
                          ),
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // 注册提示
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Don't have an account? ",
                      ).inter(fontSize: 14.sp, color: Colors.grey),
                      GestureDetector(
                        onTap: viewModel.navigateToRegister,
                        child: Text('Sign up').blackHanSans(
                          fontSize: 16.sp,
                          color: MagmaColor.purple,
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 24.h),

                  // 登录按钮
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: SizedBox(
                      width: double.infinity,
                      height: 58.h,
                      child: ElevatedButton(
                        onPressed: () => viewModel.performLogin(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: MagmaColor.purple,
                          foregroundColor: MagmaColor.black,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(100.r),
                          ),
                          elevation: 0,
                        ),
                        child: Text('Log In').blackHanSans(
                          color: MagmaColor.black,
                          fontWeight: FontWeight.w600,
                          fontSize: 24.sp,
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // Apple 登录按钮
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40.w),
                    child: SizedBox(
                      width: double.infinity,
                      height: 58.h,
                      child: ElevatedButton(
                        onPressed: () {
                          viewModel.performAppleLogin(context);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(13.r),
                            side: BorderSide(
                              color: Colors.white.withOpacity(0.44),
                              width: 1,
                            ),
                          ),
                          elevation: 0,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.apple, color: Colors.white, size: 20.sp),
                            SizedBox(width: 8.w),
                            Text('Continue with Apple').inter(
                              fontSize: 14.sp,
                              color: MagmaColor.white,
                              fontWeight: FontWeight.w400,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  Spacer(),

                  // 底部条款
                  Padding(
                    padding: EdgeInsets.only(bottom: 44.h),
                    child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 12.sp,
                        ),
                        children: [
                          const TextSpan(text: 'By Continuing you agree with '),
                          WidgetSpan(
                            child: GestureDetector(
                              onTap:
                                  () => MagmaUrl.openUrl(
                                    MagmaConstant.termsOfServiceUrl,
                                  ),
                              child: Text(
                                'Terms of Service',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp,
                                  decoration: TextDecoration.underline,
                                  decorationColor: MagmaColor.white,
                                ),
                              ),
                            ),
                          ),
                          const TextSpan(text: ' & '),
                          WidgetSpan(
                            child: GestureDetector(
                              onTap:
                                  () => MagmaUrl.openUrl(
                                    MagmaConstant.privacyPolicyUrl,
                                  ),
                              child: Text(
                                'Privacy Policy',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp,
                                  decoration: TextDecoration.underline,
                                  decorationColor: MagmaColor.white,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
